package org.huntaway.webtools.preprocessor.imp;

import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.math.BigDecimal;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.huntaway.kernel.NutException;
import org.huntaway.kernel.imp.TimesToolsImp;
import org.huntaway.webtools.preprocessor.IPreprocessor;

public abstract class BasePreprocessor<T> implements IPreprocessor {
	TimesToolsImp ttl=new TimesToolsImp();
	protected String getListHql(Class<?> clazz) {
		return "from " + clazz.getName();
	}

	protected Field getFielld(Class<?> clazz, String name) {
		Map<String, Field> fieldMap = new HashMap<String, Field>();
		getAllField(clazz, fieldMap);
		Field item = fieldMap.get(name);
		return item;
	}

	protected void setValue(Field fieldItem, Object obj, String str)
			throws IllegalArgumentException, IllegalAccessException {
		if (fieldItem.getType().equals(String.class)) {
			fieldItem.set(obj, str);
			return;
		}
		if (fieldItem.getType().equals(Integer.class)) {
			fieldItem.set(obj, Integer.parseInt(str));
			return;
		}
		if (fieldItem.getType().equals(java.util.Date.class)) {
			fieldItem.set(obj, getDate(str));
			return;
		}
		if (fieldItem.getType().equals(BigDecimal.class)) {
			fieldItem.set(obj, new BigDecimal(str));
			return;
		}		
	}

	private Date getDate(String str) {		
		try {
			return ttl.str2Time(str, TimesToolsImp.STY_24);
		} catch (NutException e) {
			e.printStackTrace();
		}
		return null;
	}

	private void getAllField(Class<?> clazz, Map<String, Field> fieldMap) {
		if (clazz.equals(Object.class)) {
			return;
		}
		Class<?> superClazz = clazz.getSuperclass();
		getAllField(superClazz, fieldMap);
		Field[] allField = clazz.getDeclaredFields();
		for (int i = 0; i < allField.length; i++) {
			Field item = (Field) allField[i];
			fieldMap.put(item.getName(), item);
		}
	}

	protected T setItemValue(HttpServletRequest request, T item) {
		Enumeration<String> requestEnum = request.getParameterNames();
		while (requestEnum.hasMoreElements()) {
			String name = requestEnum.nextElement().toString();
			try {
				String str = request.getParameter(name);
				if (str == null || str.equals("")) {
					continue;
				}
				Field fieldItem = getFielld(item.getClass(), name);
				if (fieldItem == null
						|| Modifier.isFinal(fieldItem.getModifiers())) {
					continue;
				}
				fieldItem.setAccessible(true);
				setValue(fieldItem, item, str);
			} catch (IllegalArgumentException e) {
				e.printStackTrace();
				continue;
			} catch (IllegalAccessException e) {
				e.printStackTrace();
				continue;
			}
		}
		return item;
	}
}
